package com.cskaoyan.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {

    // 数据源
    static DataSource dataSource;

    public static DataSource getDataSource() {
        return dataSource;
    }

    // 初始化
    static {

        try {
            Properties properties = new Properties();

            ClassLoader classLoader = DruidUtils.class.getClassLoader();
//            URL url = classLoader.getResource("druid.properties");
//            String path = url.getPath();
//            FileInputStream fileInputStream1 = new FileInputStream(path);

            // 获取classes路径下的文件流
            InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties");


            properties.load(resourceAsStream);

            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection =  dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
